package cn.iocoder.yudao.module.erp.service.customerinfo;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customeraccount.CustomerAccountDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.monthplaninfo.MonthPlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.mysql.contractinfo.ContractInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.customeraccount.CustomerAccountMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.monthplaninfo.MonthPlanInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.customerinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.customerinfo.CustomerInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 客户信息 Service 实现类
 *
 * @author mhc
 */
@Service
@Validated
public class CustomerInfoServiceImpl implements CustomerInfoService {

    @Resource
    private CustomerInfoMapper customerInfoMapper;

    @Resource
    private CustomerAccountMapper customerAccountMapper;

    @Resource
    private MonthPlanInfoMapper monthPlanInfoMapper;

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Override
    public Long createCustomerInfo(CustomerInfoSaveReqVO createReqVO) {

        // 插入
        CustomerInfoDO customerInfo = BeanUtils.toBean(createReqVO, CustomerInfoDO.class);

        customerInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());


        customerInfo.setNowCount(new BigDecimal("0"));
        customerInfo.setSaleCount(new BigDecimal("0"));
        customerInfo.setBuyCount(new BigDecimal("0"));
        customerInfo.setRemark("");


        try{
        customerInfoMapper.insert(customerInfo);
        }catch (Exception e){
            if (e instanceof java.sql.SQLIntegrityConstraintViolationException) {
                throw  exception(new ErrorCode(1_10_1,"公司名称存在重复，请修改后再试！"));
            } else {
                e.printStackTrace();
                throw exception(new ErrorCode(1_10_1,"数据丢失，请刷新后再试!"));
            }
        }

        //同步创建
       /* CustomerAccountDO a=new CustomerAccountDO();
        a.setBuyCount(new BigDecimal("0"));
        a.setCustomerId(customerInfo.getId());
        a.setNowCount(new BigDecimal("0"));
        a.setSaleCount(new BigDecimal("0"));
        a.setRemark("");
        customerAccountMapper.insert(a);*/


        // 返回
        return customerInfo.getId();
    }

    @Override
    public void updateCustomerInfo(CustomerInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerInfoExists(updateReqVO.getId());
        // 更新
        CustomerInfoDO updateObj = BeanUtils.toBean(updateReqVO, CustomerInfoDO.class);
        customerInfoMapper.updateById(updateObj);

       /* CustomerAccountDO a=new CustomerAccountDO();
        a.setBuyCount(new BigDecimal("0"));
        a.setCustomerId(updateObj.getId());
        a.setNowCount(new BigDecimal("0"));
        a.setSaleCount(new BigDecimal("0"));
        a.setRemark("");
        customerAccountMapper.insert(a);*/
    }

    @Override
    @Transactional
    public void deleteCustomerInfo(Long id) {
        // 校验存在
        validateCustomerInfoExists(id);
        // 删除
        //判断是否可删除
        long ec=monthPlanInfoMapper.selectCount(new LambdaQueryWrapperX<MonthPlanInfoDO>().eq(MonthPlanInfoDO::getSaleCustomerId,id).or().eq(MonthPlanInfoDO::getBuyCustomerId,id));
        if(ec>0){
            throw exception(new ErrorCode(1_1_1_0,"此数据以关联月度计划，不可删除！"));
        }


        long pc=planInfoMapper.selectCount(new LambdaQueryWrapperX<PlanInfoDO>().eq(PlanInfoDO::getSaleCustomerId,id).or().eq(PlanInfoDO::getBuyCustomerId,id));
        if(pc>0){
            throw exception(new ErrorCode(1_1_1_1,"此数据以关联每日计划，不可删除！"));
        }


        long cc=contractInfoMapper.selectCount(new LambdaQueryWrapperX<ContractInfoDO>().eq(ContractInfoDO::getCustomerId,id));
        if(cc>0){
            throw exception(new ErrorCode(1_1_1_2,"此数据以关联合同，不可删除！"));
        }



        customerInfoMapper.deleteById(id);

        customerAccountMapper.delete(CustomerAccountDO::getCustomerId,id);


    }

    private void validateCustomerInfoExists(Long id) {
        if (customerInfoMapper.selectById(id) == null) {
            throw exception(CUSTOMER_INFO_NOT_EXISTS);
        }
    }

    @Override
    public CustomerInfoDO getCustomerInfo(Long id) {
        return customerInfoMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerInfoDO> getCustomerInfoPage(CustomerInfoPageReqVO pageReqVO) {
        return customerInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<CustomerInfoDO> getCustomerAccountInfoPage(CustomerInfoPageReqVO pageReqVO) {
        return customerInfoMapper.selectAccountPage(pageReqVO);
    }

    @Override
    public List<CustomerInfoDO> getCustomerListByStatus(Integer status) {
        return customerInfoMapper.selectListByStatus(status);
    }

    @Override
    public List<CustomerInfoDO> getCustomerListIds(Collection<Long> inIds) {
        if (CollUtil.isEmpty(inIds)) {
            return Collections.emptyList();
        }
        return customerInfoMapper.selectListByInIds(inIds);
    }



}